<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once 'Uploader.php';

/**
 * Extension of the abstract Uploader class for basic files. 
 * 
 * @package CodeIgniter
 * @subpackage Libraries
 * @category Libraries
 * @author davidmorris
 * @see Uploader
 */
class FileUploader extends Uploader {
    
    /**
     * Basically provides an way of inserting generic files. Files are inserted 
     * into files_table, the newly created id for that file is then inserted into
     * the required field as part of a new row for the table provided in the constructor.
     * 
     * @todo Once the session and logging in stuff is done, insert the user's id instead of just 1
     * @param string $formField the file upload element
     * @param array $dbFieldsValues the assocative array for values for insertion "column" => "value"
     * @return int the new file id
     */
    public function insert($formField, $dbFieldsValues = array())
    {  
        $fileName = $this->moveFile($formField);
        if($fileName === false)
            return false;       
        $this->CI->db->query('INSERT INTO files_table (file_location, file_type, file_uploaded, file_owner) VALUES (?, ?, UNIX_TIMESTAMP(), 1)',
            array($this->Dir.'/'.$fileName, $_FILES[$formField]['type']));
        
        $newFileId = $this->CI->db->insert_id();
        $dbFieldsValues[$this->Field] = $newFileId;
        $columns = $this->prepareColumns(array_keys($dbFieldsValues));
        $values = implode(', ',array_pad(array(),count($dbFieldsValues),'?'));
        $this->CI->db->query('INSERT INTO `'.$this->Table.'` ('.$columns.') VALUES ('.$values.')',
            array_values($dbFieldsValues));
        
        return $newFileId;
    }
}
// END OF FILE